<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item
          ><div class="div1">基本配置</div></el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><div class="div2">平台管理</div></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 teamManage -->
    <!-- 添加团队 -->
    <div class="content">
      <h2>平台管理</h2>
      <h3>数据筛选</h3>
      <div>
        <el-form :inline="true" id="search" size="small">
          <el-form-item label="平台名称">
            <el-input
              v-model="search.name"
              clearable
              placeholder="请输入平台名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select
              v-model="search.platform_type_value"
              placeholder="请选择类型"
              clearable
            >
              <el-option
                v-for="item in dictionaries.platform_type"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="search.enable_status_value"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="item in dictionaries.enable_status"
                :key="item.dictId"
                :label="item.dictName"
                :value="item.dictId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData('search')"
              >查询</el-button
            >
            <el-button
              type="primary"
              plain
              @click="fetchData('reset')"
              >重置</el-button
            ></el-form-item
          >
        </el-form>
      </div>
    </div>
    <div class="content">
      <h3 class="data-list-title">数据列表
        <el-button
          v-if="parArray.indexOf('addPlatform') != -1"
          size="small"
          type="primary"
          @click="showDialog('新增', 'add')"
      >新增</el-button
      ></h3>

      <!-- <div>{{ parArray.indexOf("authorityAdd") == 1 }}{{ parArray }}</div> -->
      <lb-table
        :column="column"
        :data="platformList"
        pagination
        :total="page.totalNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 30, 50]"
        :current-page.sync="page.currentPage"
        :page-size="page.pageSize"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>
    </div>
    <!-- 管理客户等级 -->

    <!-- ============================= el-dialog ============================= -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="30%"
      :append-to-body="true"
      :before-close="handleClose"
      class="platform-dialog"
    >
      <div class="dialog-content">
        <div>
          <el-form
            :model="platformForm"
            :rules="platformRules"
            ref="platformForm"
            label-width="100px"
          >
            <el-form-item label="平台名称" prop="name" >
              <el-input v-model="platformForm.name" size="mini" maxlength="20" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="平台编码" prop="code">
              <el-input v-model="platformForm.code" size="mini" maxlength="6" show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select
                v-model="platformForm.type"
                placeholder="请选择类型"
                size="mini"
                clearable
              >
                <el-option
                  v-for="item in dictionaries.platform_type"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="序号" prop="sort">
              <el-input
                v-model.number="platformForm.sort"
                size="mini"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="状态"
              prop="status"
              v-if="dialog.type === 'add'"
            >
              <el-radio-group v-model="platformForm.status">
                <el-radio
                  v-for="item in dictionaries.enable_status"
                  :key="item.dictId"
                  :value="item.dictId"
                  :label="item.dictName"
                  :name="item.dictId"
                ></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- ============================= el-dialog end ============================= -->
  </div>
</template>

<script>
import { checkCode, checkSort } from '@/utils/rules.js';
import LbTable from '../../../components/lb-table/lb-table'
export default {
  name: 'role',
  components: { LbTable },
  data () {
    return {
      search: {
        name: '',
        platform_type_value: '',
        enable_status_value: '',
      },
      platformList: [],
      column: [
        { label: '平台', prop: 'name' },
        { label: '平台编码', prop: 'code' },
        { label: '类型', prop: 'typeLabel' },
        { label: '店铺数', prop: 'shopCount' },
        { label: '序号', prop: 'sort' },
        {
          label: '状态',
          render: (h, scope) => {
            return (
              <div>
                <el-link size="mini" type={scope.row.status === 1 ? 'success' : 'danger'}>{scope.row.statusLabel}</el-link>
              </div>
            )
          }
        },
        { label: '最后更新时间', prop: 'updatedTime' },
        {
          label: '操作',
          render: (h, scope) => {
            return (
              <div>
                <el-link size="mini" type="primary" onClick={() => { this.showDialog('编辑', 'edit', scope.row, scope.$index) }}>编辑</el-link>
                <el-link size="mini" type="danger" onClick={() => { this.onDelete(scope.row, scope.$index) }}>删除</el-link>
                <el-link size="mini" type="primary" onClick={() => { this.changeStatus(scope.row, scope.$index) }} >{scope.row.status === 1 ? "禁用" : "启用"}</el-link>
              </div>
            )
          }


        }],
      page: { pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 },
      dialog: { visible: false, title: "编辑", type: '' },
      platformForm: {
        name: '', // 平台名称 string
        code: '', // 平台编码 string
        type: '', // 类型 string
        sort: '', // 序号 int
        status: '1' // 状态 string
      },
      platformRules: {
        name: [
          { required: true, message: '请输入平台名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入平台编码', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' },
          { validator: checkCode, message: '只能输入数字或英文字母',trigger: 'change' },
          { validator: checkCode, message: '只能输入数字或英文字母',trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择类型', trigger: 'change' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }],
        sort: [{ validator: checkSort, trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
      dictionaries: { // 字典数据
        platform_type: [], // 类型
        enable_status: [], // 状态
      },
      parArray: [] // 按钮权限
    };
  },
  created () {
    this.fetchData()
    this.getButtonTreeDto() // 获取权限设定
    // 获取字典值
    for (let type in this.dictionaries) { this.getDictionaries(type) }
  },
  /*
  watch: {
    permissionFilterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  */
  methods: {
    fetchData (type) {
      if (type == 'reset') {
        this.search.name = ''
        this.search.platform_type_value = ''
        this.search.enable_status_value = ''
        this.page.pageNo = 1
        this.page.pageSize = 10
        this.page.currentPage = 1
      }
      const params = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      }
      if (type == 'search') {
        this.page.currentPage = 1
        this.page.pageNo = 1
        params.pageNo = 1
        const search = this.search
        params.name = search.name
        params.type = search.platform_type_value
        params.status = search.enable_status_value

        // 去除字符串 前后 空格
        for (let item in params) { if(typeof params[item] === "string"){ params[item] = params[item].trim() } }
      }
      this.$api.platformList(params).then((res) => {
        this.platformList = res.data.list
        this.page.totalNum = res.data.totalNum

      }).catch((err) => {
        console.log(err)
      })
    },
    handleCurrentChange (currentChange) {
      this.page.pageNo = currentChange
      this.fetchData()
    },
    handleSizeChange (sizeChange) {
      this.page.pageSize = sizeChange
      this.fetchData()
    },
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
        (item) => item.menuCode === 'platformCode'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })
      console.log(this.parArray, "this.parArray")
    },
    // 获取字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
        // 补始启用状态
        if(type === "enable_status"){
          console.log(type)
          this.platformForm.status = res.data[0].dictName
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 显示  dialog
    showDialog (title, type, row) {
      this.dialog.type = type
      this.currentRow = row
      if (type == 'edit') {
        if (this.parArray.indexOf('editPlatform') == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }
        this.dialog.visible = true;
        this.dialog.title = '编辑';
        this.platformForm = row
      }
      if (type == 'add') {
        if (this.parArray.indexOf('addPlatform') == -1) { return this.$message({ type: 'warning', message: '没有权限请联系管理员!' }); }
        this.dialog.visible = true;
        this.dialog.title = '新增';
        this.platformForm = {
          name: '', // 平台名称 string
          code: '', // 平台编码 string
          type: '', // 类型 string
          sort: '', // 序号 int
          status: this.dictionaries.enable_status[0].dictName // 状态 string
        }
      }
      this.$refs["platformForm"].resetFields();
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    // 确认后判断各类操作
    dialogConfirm () {
      this.submitForm("platformForm")
    },
    // 表单验证
    submitForm (formName) {
      const type = this.dialog.type
      this.$refs[formName].validate((valid) => {
        if (valid) {
          switch (type) {
            case 'add':
              this.addPlatform()
              break;
            case 'edit':
              this.editPlatform()
              break;
            default:
              console.log(type)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 添加平台
    addPlatform () {
      // debugger
      const params = this.platformForm
      params.status = this.dictionaries.enable_status.find((e) => e.dictId == params.status || e.dictName == params.status).dictId
      // const params = { name: permissionForm.name, dataPermission: permissionForm.dataPermission, salesAuthorityId: permissionForm.salesAuthorityId }
      this.$api.platformAdd(params).then((res) => {
        this.platformForm = {
          name: '', // 平台名称 string
          code: '', // 平台编码 string
          type: '', // 类型 string
          sort: '', // 序号 int
          status: '' // 状态 string
        }
        this.dialog.visible = false;
        this.fetchData()
        this.$message({ type: 'success', message: '操作成功!' });
      }).catch((err) => {
        this.platformForm.status = this.dictionaries.enable_status.find((e) => e.dictId == params.status || e.dictName == params.status).dictName
        // console.log(this.platformForm)
        console.log(err)
      })
    },
    // 编辑
    editPlatform () {
      const params = this.platformForm
      // if (typeof params.status !== Number) { params.status = this.dictionaries.enable_status.find((e) => e.dictName === params.status).dictId }
      // console.log(params)
      // const params = { name: permissionForm.name, dataPermission: permissionForm.dataPermission, salesAuthorityId: permissionForm.salesAuthorityId }
      this.$api.platformUpdate(params).then((res) => {
        this.dialog.visible = false;
        this.fetchData()
        this.$message({ type: 'success', message: '编辑成功!' });
      }).catch((err) => {
        this.dialog.visible = false;
        this.fetchData()
        console.log(err)
      })
    },
    // 删除
    onDelete (item, index) {
      if (this.parArray.indexOf("deletePlatform") != -1) {
        this.$confirm('此操作将删除选中的权限组, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = { id: item.id }
          this.$api.platformDelete(data).then((res) => {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch((err) => {
            console.log(err)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$message.warning('没有权限请联系管理员！')
      }

    },
    // 修改状态
    changeStatus (item, index) {

      const data = { id: item.id }
      // 禁用
      if (item.status === 1) {
        if (this.parArray.indexOf('forbiddenPlatform') != -1) {
          this.$api.platformDisable(data).then((res) => {
            this.fetchData()
            this.$message({
              message: `已禁用【${item.name}】!`
            });
          }).catch((err) => {
            console.log(err)
          })
        } else {
          this.$message.warning('没有权限请联系管理员')
        }

      }

      // 启用
      if (item.status === 2) {
        if (this.parArray.indexOf('openPlatform') != -1) {
          this.$api.platformEnable(data).then((res) => {
            this.fetchData()
            this.$message({
              type: 'success',
              message: `启用【${item.name}】成功!`
            });
          }).catch((err) => {
            console.log(err)
          })
        } else {
          this.$message.warning('没有权限请联系管理员')
        }
      }

    },
  }
}
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.div2 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
.div3 {
  margin-left: -8px;
  background: url(../../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
//
//#search{
//  display: flex;
//  .el-form-item{
//    flex: 1;
//    .el-form-item__content{
//      width: 80%;
//    }
//  }
//}

.content {
  .el-button {
    margin-bottom: 10px;
  }
  .el-badge {
    margin-left: 10px;
  }
}
.roleList {
  border: 1px solid #f0f3fd;
  border-radius: 5px;
  .title {
    color: #333333;
    line-height: 40px;
    padding: 0 10px;
    background-color: #f0f3fd;
    .el-badge {
      margin-top: 10px;
      margin-left: 10px;
    }
  }
  .list {
    padding: 20px;
    .el-tag {
      border: 0;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
.el-dialog{
  background-color: #2D7EDF;
  .el-dialog__body{
    padding: 10px;
    .dialog-content {
      // min-height: 210px;
      .el-tree {
        max-height: 300px;
        overflow: auto;
      }
    }
  }
}

</style>
<style lang="scss">
.content {
  .el-link {
    margin: 0 5px;
  }
  h4 {
    padding-top: 10px;
    border-top: 1px solid #bbbbbb;
  }
}
.data-list-title{
  .el-button{
    float: right;
  }
}
</style>
